package cn.com.dhcc.app.pub.module.codematic.controller;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.ReflectionUtils;
import cn.com.dhcc.app.core.util.SqlUtil;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.WebUtil;
import cn.com.dhcc.app.pub.module.codematic.service.ControllerGenerator;
import cn.com.dhcc.app.pub.module.codematic.service.DaoGenerator;
import cn.com.dhcc.app.pub.module.codematic.service.ServiceGenerator;
import cn.com.dhcc.app.pub.module.codematic.service.ViewGenerator;
import cn.com.dhcc.app.pub.module.codematic.vo.Bean;
import cn.com.dhcc.app.pub.module.codematic.vo.Col;

public class ActionHandler {
	private static final String appPkg = "cn.com.dhcc.turbo";
	public final static String YES = "1";
	public final static String NO = "0";
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getDetachLogger(LOGTYPE.TURBO);
	@SuppressWarnings("rawtypes")
	public static void validateEntity(HttpServletRequest request, HttpServletResponse response) {
		String result = "fail";
		try {
			String entity = request.getParameter("entity");
			if (entity != null && !"".endsWith(entity)) {
				Class clazz = Class.forName(entity.trim());
				if (clazz != null) {
					result = "success";
				}
			}
		} catch (Exception e) {
			logger.error(e);
		} finally {
			WebUtil.renderText(response, result);
		}
	}

	@SuppressWarnings("rawtypes")
	public static void entityForm(HttpServletRequest request, HttpServletResponse response) {
		try {
			String entity = request.getParameter("entity");
			String moduleUri = StrUtil.substringAfterLast(StrUtil.substringBeforeLast(entity, "."), ".");

			Class clazz = Class.forName(entity.trim());
			List<Field> fieldList = ReflectionUtils.getDeclaredFieldsCasecade(clazz);
			List<Col> colList = new ArrayList<Col>();
			for (Field field : fieldList) {
				if (!"serialVersionUID".equalsIgnoreCase(field.getName())) {
					Col col = new Col();
					col.setName(field.getName());
					col.setNameCN(field.getName());
					col.setShow(true);
					col.setSearch(true);
					col.setType(field.getType().getSimpleName());
					colList.add(col);
				}
			}
			request.setAttribute("moduleUri", moduleUri);
			request.setAttribute("entity", entity.trim());
			request.setAttribute("data_list", colList);
			request.getRequestDispatcher("entity_form.jsp").forward(request, response);
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public static void genCode(HttpServletRequest request, HttpServletResponse response) {
		Status status = Status.getInstance();
		try {
			String appRoot = request.getSession().getServletContext().getRealPath("/");
			String entity = getParameterWithTrim(request, "entity");
			String entityPkg = getParameterWithTrim(request, "entityPkg");
			String daoPkg = getParameterWithTrim(request, "daoPkg");
			String servicePkg = getParameterWithTrim(request, "servicePkg");
			String controllerPkg = getParameterWithTrim(request, "controllerPkg");
			String moduleUri = getParameterWithTrim(request, "moduleUri");
			String viewPkg = getParameterWithTrim(request, "viewPkg");

			Class<?> clazz = Class.forName(entity);
			String beanName = clazz.getSimpleName();
			String beanUri = SqlUtil.addUnderscores(beanName);

			String ords = getParameterWithTrim(request, "ords");

			String[] orders = ords.split(",");
			List<Col> colList = new ArrayList<Col>();
			List<Col> formFieldList = new ArrayList<Col>();
			for (String field : orders) {
				String nameCN = getParameterWithTrim(request, field + "_cn");
				String show = getParameterWithTrim(request, field + "_show");
				String search = getParameterWithTrim(request, field + "_search");
				String validate = getParameterWithTrim(request, field + "_validate");
				String ajaxCheck = getParameterWithTrim(request, field + "_ajaxCheck");
				String formField = getParameterWithTrim(request, field + "_formField");
				String formType = getParameterWithTrim(request, field + "_formType");
				String[] optionVals = getParameterValues(request, field + "_select_option_val");
				String[] optionNames = getParameterValues(request, field + "_select_option_name");

				Col col = new Col();
				col.setName(field);
				col.setNameCN(nameCN);
				col.setFormField(YES.equals(formField));
				col.setFormType(formType);
				col.setShow(YES.equals(show));
				col.setSearch(YES.equals(search));
				col.setValidate(YES.equals(validate));
				col.setAjaxCheck(YES.equals(ajaxCheck));
				Field f = clazz.getDeclaredField(field);
				col.setType(f.getType().getSimpleName());
				if (col.isShow()) {
					colList.add(col);
				}
				if (col.isFormField()) {
					formFieldList.add(col);
				}

				if ("select".endsWith(col.getFormType())) {
					Map<String, String> optionMap = new HashMap<String, String>();
					for (int i = 0; i < optionVals.length; i++) {
						optionMap.put(optionVals[i], optionNames[i]);
					}
					col.setOptionMap(optionMap);
				}
			}

			Bean bean = new Bean();
			bean.setBeanName(beanName);
			bean.setAppPkg(appPkg);
			bean.setEntityPkg(entityPkg);
			bean.setDaoPkg(daoPkg);
			bean.setServicePkg(servicePkg);
			bean.setControllerPkg(controllerPkg);
			bean.setModuleUri(moduleUri);
			bean.setBeanUri(beanUri);
			bean.setViewPkg(viewPkg);
			bean.setViewColList(colList);
			bean.setFormColList(formFieldList);

			//每次生成代码之前，先删掉之前的代码 meow~
			String genRoot = appRoot + "/codematic/main";
			new File(genRoot).delete();
			
			String codeRoot = appRoot + "/codematic/main";
			File codeRootDir = new File(codeRoot);
			if(!codeRootDir.exists()){
				codeRootDir.mkdirs();
			}

			
			DaoGenerator.generate(appRoot,clazz, bean);
			ServiceGenerator.generate(appRoot,clazz, bean);
			ControllerGenerator.generate(appRoot,clazz, bean);
			ViewGenerator.generate(appRoot,clazz, bean);

			status.setMsg("操作成功");
			status.setSuccess(true);
		} catch (Exception e) {
			logger.error(e);
			status.setSuccess(false);
			status.setMsg("操作失败：" + e.fillInStackTrace());
		}
		WebUtil.renderJson(response, status);
	}

	public static String getParameterWithTrim(HttpServletRequest request, String name) {
		name = request.getParameter(name);
		if (StrUtil.isNotBlank(name)) {
			name = name.trim();
		}
		return name;
	}

	public static String[] getParameterValues(HttpServletRequest request, String name) {
		return request.getParameterValues(name);
	}
}
